import { Category } from '../../pages/category/category-model.js';

var category = new Category();

Page({
  data: {
    transClassArr: ['tanslate0', 'tanslate1', 'tanslate2', 'tanslate3', 'tanslate4', 'tanslate5'],
    currentMenuIndex:0,
    loadingHidden: false,
  },
  onLoad: function (options) {
    this._loadData();
  },
  onReady: function () {

  },
  _loadData: function () {
    category.getCategoryType((categoryData) => {
      this.setData({
        categoryTypeArr: categoryData
      });
      category.getProductByCategory(categoryData[0].id,(data)=>{
        var dataObj = {
          products: data,
          topImgUrl: categoryData[0].topic_img.url,
          title: categoryData[0].name,
        };
        this.setData({
          categoryInfo0: dataObj,
          loadingHidden: true,
        });
      });
    });
  },
  // 分类导航跳转
  changeCategory: function (event) {
    var index = category.getDataSet(event, 'index'),
      id = category.getDataSet(event, 'id')//获取data-set
    this.setData({
      currentMenuIndex: index
    });

    //如果数据是第一次请求
    if (!this.isLoadedData(index)) {
      var that = this;
      category.getProductByCategory(id, (data) => {
        that.setData(that.getDataObjForBind(index, data));
      });
    }
  },

  isLoadedData: function (index) {
    if (this.data['categoryInfo' + index]) {
      return true;
    }
    return false;
  },

  getDataObjForBind: function (index, data) {
    var obj = {},
      arr = [0, 1, 2, 3, 4, 5],
      baseData = this.data.categoryTypeArr[index];
    for (var item in arr) {
      if (item == arr[index]) {
        obj['categoryInfo' + item] = {
          products: data,
          topImgUrl: baseData.topic_img.url,
          title: baseData.name
        };

        return obj;
      }
    }
  },
  // 产品页面跳转
  onProductItemTap: function (event) {
    var id = category.getDataSet(event, 'id');
    var name = category.getDataSet(event, 'name');
    wx.navigateTo({
      url: '../product/product?id=' + id + '&name=' + name,
    })
  },
})